import React, { useState, useEffect, useRef } from 'react'
import { inject, observer } from 'mobx-react'

import VideoInfo from '../../right-menu/vidoe-info'
import { getPath, MouseInScreen, focusScreen, setPlayingScreens } from '../../../util'
import video from '../../../store/video'
import recordTime from '@/store/record-time'
import common from '../../../store/common'
import '../styles/screen.scss'

const style = {
  border: '1px solid white',
  boxSizing: 'border-box',
}
let dragId = ''

const Screen = ({ id, customStyle }) => {
  const { event$ } = common

  const [dropId, setDropId] = useState(null)
  const [dropPos, setDropPos] = useState({ x: 0, y: 0 })

  const ref = useRef()

  useEffect(() => {
    if (dragId && dropId) {
      const { player: dragPlayer } = video.findScreenById(dragId)
      const { player: dropPlayer } = video.findScreenById(dropId)
      if (dragPlayer || dropPlayer) {
        exchangeScreen(dragId, dropId)
      }
      focusScreen(dropId)
      dragId = null
      setDropId(null)
    }
  }, [dropId])

  // 拖拽释放的位置
  useEffect(() => {
    const { x, y } = dropPos
    const screen = MouseInScreen(x, y)
    if (screen) {
      focusScreen(screen.screenId)
    }
  }, [dropPos])

  function exchangeScreen(dragId, dropId) {
    video.exchangeScreen(dragId, dropId)
    const dragScreen = document.getElementById(dragId)
    const dropScreen = document.getElementById(dropId)
    const dragChild = dragScreen.firstChild
    const dropChild = dropScreen.firstChild
    const child = dropScreen.replaceChild(dragChild, dropChild)
    dragScreen.append(child)
    // 如果两个分屏都在播放视频，将一个视频标签移过来后，再把原来的视频标签移出去
    if (dropScreen.firstChild.childNodes.length > 0) {
      const actions = ['stopVideo', 'stopVideo', 'playVideo', 'playVideo']
      const ids = [dragId, dropId, dragId, dropId]
      setPlayingScreens(actions, ids)
    } else {
      const actions = ['stopVideo', 'playVideo']
      const ids = [dragId, dropId]
      setPlayingScreens(actions, ids)
    }
    recordTime.exchangeId(dragId, dropId)
  }

  function onDragStart({ target }) {
    document.body.ondragover = (e) => {
      e.preventDefault()
    }
    dragId = target.id
  }

  function onDragEnd({ clientX, clientY }) {
    const screen = MouseInScreen(clientX, clientY)
    if (screen) {
      setDropId(screen.id)
      setDropPos({ x: clientX, y: clientY })
    }
  }

  function handleWheel(e) {
    const { nativeEvent } = e
    const { wheelDelta, path } = nativeEvent
    const i = wheelDelta > 0 ? -1 : 1
    const step = 2
    const id = getPath(path).id
    if (id.indexOf('screen') !== -1) {
      const screen = video.findScreenById(id)
      const _video = screen.player?.video
      const { currentTime, duration } = _video
      // 调整video当前时间
      _video.currentTime = Math.max(Math.min(currentTime + i * step, duration), 0)
    }
  }

  return (
    <div
      id={id}
      ref={ref}
      style={{ ...style, ...customStyle }}
      onMouseDown={() => focusScreen(ref.current.id)}
      draggable="true"
      onDragStart={onDragStart}
      onDragOver={(e) => e.preventDefault()}
      onDragEnd={onDragEnd}
      onContextMenu={(e) => {
        e.preventDefault()
        const { clientX: x, clientY: y } = e
        event$.emit({ action: 'showRightMenu', val: { pos: { x, y }, screenId: ref.current.id } })
      }}
      onWheel={(e) => handleWheel(e)}
    >
      <div style={{ width: '100%', height: '100%', display: 'flex' }}>
        <VideoInfo />
        <div className="video-container" />
      </div>
    </div>
  )
}

export default inject('store')(observer(Screen))
